<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

function p($data){
    echo '<pre>';
    print_r($data);
    echo '</pre>';
    die();
}

/**
 * 获取请求头部信息
 */
if (!function_exists('getallheaders')) {
    function getallheaders() {
        foreach ($_SERVER as $name => $value) {
            if (substr($name, 0, 5) == 'HTTP_') {
                $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
            }
        }
        return $headers;
    }
}

/**
 * 登录验证
 * @return mixed
 */
function check_login()
{
    $header = getallheaders();
    // 判断是否存在对应的user_id,AppAuthorization,expire_time
    if (!isset($header['user_id']) || !isset($header['AppAuthorization']) || !isset($header['expire_time'])){
        error('非法请求');
    }

    //缺少token
    if (is_null($header['AppAuthorization'])) {
        error('miss token');
    }

    $signer = new \Lcobucci\JWT\Signer\Hmac\Sha256();
    try{
        $token  = (new Lcobucci\JWT\Parser())->parse((string)$header['AppAuthorization']);
    }catch (\Exception $e){
        error($e->getMessage());
    }

    //验证成功后给当前uid赋值
    if (true == ($token->verify($signer, config('app_key')))) {
        return $token->getClaim('uid');
    }else{
        error('token error');
    }
}


//成功返回
function success($msg = 'success', $data = '',  $code = 1, $type = 'json', array $header = [])
{
    return_result($data, $code, $msg, $type, $header);
}


//失败返回
function error($data = '', $msg = 'fail', $code = 0, $type = 'json', array $header = [])
{
    return_result($data, $code, $msg, $type, $header);
}

//返回结果，参考tp自带result方法
function return_result($data, $code = 0, $msg = '', $type = 'json', array $header = [])
{
    $msg = lang($msg, [], config('default_lang'));
    $result = [
        'code' => $code,
        'msg'  => $msg,
        'time' => time(),
        'data' => $data,
    ];

    $type     = $type ?: $this->getResponseType();
    $response = \think\Response::create($result, $type)->header($header);

    throw new think\exception\HttpResponseException($response);
}

/**
 * redis 连接
 * @return Redis
 */
function redis_connent()
{
    $redis = new Redis();
    return $redis;
}

/**
 * 将数组key的值变成键
 * @param $array
 * @param $key
 */
function val_2_key($array,$key){
    $return_data = [];
    if (is_array($array)){
        foreach ($array as $k => $v){
            $return_data[$v[$key]] = $v;
        }
    }
}

/**
 * 随机生成固定长度的数字验证码
 * @param int $length
 * @return string
 */
function auto_code($length = 4){
    $num="";
    for($i = 0; $i < $length; $i++){
        $num .= rand(0,9);
    }
    return $num;
}

/**
 * 获取加盐密码
 * @param string $password 用户输入的明文密码
 * @return array
 */
function get_salt_password($password) {
    $salt = substr(md5(rand(1000, 9999) . microtime()), -10);
    return [
        'salt' => $salt,
        'password' => md5($password . $salt)
    ];
}

/**
 * 验证加盐密码
 * @param   string   $password          用户输入的明文密码
 * @param   string   $encode_pwd        用户的加密密码
 * @param   string   $encode_pwd_salt   加密盐
 * @return bool
 */
function verify_salt_password($password, $encode_pwd, $encode_pwd_salt) {
    return $encode_pwd == md5($password . $encode_pwd_salt);
}

